﻿define(function (require, exports, module) {
    var Config = require('config');
    var m_cache = [];

    function Canvas(index) {
        this.Index = index;
    }

    Canvas.prototype.Jquery = function () {
        var args = Array.prototype.slice.call(arguments);
        var dom = m_cache[this.Index].Dom;
        return dom[args.shift()].apply(dom, args);
    };

    Canvas.prototype.Bind = function (module, options) {
        m_cache[this.Index].Handlers[module] = options;
    };

    Canvas.prototype.Unbind = function (module) {
        delete m_cache[this.Index].Handlers[module];
    };

    Canvas.prototype.Call = function () {
        var args = Array.prototype.slice.call(arguments);
        var ctx = m_cache[this.Index].Ctx;
        return ctx[args.shift()].apply(ctx, args);
    };

    Canvas.prototype.Set = function (name, value) {
        m_cache[this.Index].Ctx[name] = value;
        return this;
    };

    Canvas.prototype.ChangeFont = function (size, bold) {
        m_cache[this.Index].Ctx.font = [size, 'px 微软雅黑', 'boolean' == typeof bold && bold ? ' bold' : ''].join('');
    };

    Canvas.prototype.Clear = function () {
        m_cache[this.Index].Ctx.clearRect(0, 0, Config.GetWidth(), Config.GetHeight());
    };

    //Handlers格式为: { 功能名: { 事件名: {} } }
    $('canvas').each(function (i) {
        var canvas = { Instance: new Canvas(i), Dom: $(this), Ctx: this.getContext('2d'), Handlers: {} };
        m_cache.push(canvas);
        if (i) return true;

        var domEvents = {};
        $.each(['click', 'mousedown', 'mousemove', 'mouseout', 'mouseup'], function () {
            var eventName = this.toString();
            domEvents[eventName] = function (e) {
                $.each(m_cache, function () {
                    var preventEvent = false;
                    $.each(this.Handlers, function (module, events) {
                        if (events.hasOwnProperty(eventName)) {
                            var eventResult = events[eventName](e);
                            'boolean' == typeof eventResult && (preventEvent = !eventResult);
                        }
                    });
                    if (preventEvent)
                        return false;
                });
            }
        });
        canvas.Instance.Jquery('bind', domEvents);
    });

    exports.Init = function () {
        $.each(m_cache, function (i) {
            this.Dom.attr({ width: Config.GetWidth(), height: Config.GetHeight() });
            this.Instance.ChangeFont(12, true);
        });
    };

    exports.Get = function (index) {
        'number' == typeof index || (index = 0);
        return m_cache[index].Instance;
    };
});